import json
import random
import requests
from ..config.config import Config


class UnitReply:
    def __init__(self):
        self.config = Config

    def unit_chat(self):
        #获取access_token
        url = f"{self.config.access_token}&client_id={self.config.client_id}&client_secret={self.config.client_secret}&"

        #发送请求
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }

        response = requests.request("POST", url, headers=headers)

        #access_token
        access_token = response.json()['access_token']

        return access_token

    def unit_chat_reply(self, chat_input):
        """
        智能回复
        :return:
        """
        access_token =  self.unit_chat()
        url = f'{self.config.unit_reply_url}?access_token={access_token}'
        #定义请求参数
        post_data = {
            "log_id" : str(random.random()),
            "request" : {
                "query" : chat_input,
                "terminal_id" : "88888"
            },
            "session_id" : "",
            "service_id" : self.config.service_id,
            "version" : "3.0"
        }
        response = requests.post(url, json=post_data)
        unit_chat_obj = json.loads(response.content)
        unit_reply = "不好意思，我现在很忙"
        if unit_chat_obj["error_code"] != 0: return  unit_reply
        unit_chat_obj_reply = unit_chat_obj["result"]["responses"][0]["actions"][0]["say"]
        return unit_chat_obj_reply
